const router = require("koa-router")();
const jwt = require("jsonwebtoken");

const generateCode = require("../utils/generateCode");
const isCorrectPassword = require("../utils/md5");
const writeJSON = require("../utils/writeJOSN");
const { secret } = require("../config");
const knex = require("../config/knex");
const setResponse = require("../utils/api");

// 1. 登录
router.post("/login", async (ctx) => {
  const { phone, password } = ctx.request.body;
  if (!phone || !password) {
    ctx.body = {
      message: "账号密码不能为空!!",
    };
    return;
  }
  const users = await knex("users").where({ phone }).select("*");
  console.log(users);
  if (users.length > 0) {
    const { password: loginPassword, ...rest } = users[0];
    const isCorrect = isCorrectPassword(loginPassword, password);
    if (isCorrect) {
      const token = jwt.sign({ phone }, secret, { expiresIn: "1h" });
      writeJSON(ctx, 200, { token, userInfo: { ...rest } }, "登录成功");
      return;
    }
  }
  writeJSON(ctx, 401, null, "登录失败，密码错误");
});

// 2. 注册
router.post("/register", async (ctx) => {
  const { phone, password, nickname } = ctx.request.body;
  if (!phone || !password || !nickname) {
    ctx.body = {
      message: "账号密码不能为空!!",
    };
    return;
  }
  try {
    await knex("users").insert({
      phone,
      password,
      nickname,
      roleType: 2, // 普通用户
      avatarUrl: "",
    });
    writeJSON(ctx, 200, null, "注册成功");
  } catch (error) {
    console.log(error);
    writeJSON(ctx, 500, null, "服务器异常");
  }
});

// 3. 添加一个用户
router.post("/add", async (ctx) => {
  const { phone, password, nickname, roleType, avatarUrl } = ctx.request.body;
  try {
    await knex("users").insert({
      phone,
      password,
      nickname,
      roleType,
      avatarUrl,
    });
    writeJSON(ctx, 200, null, "添加用户成功！");
  } catch (error) {
    console.log(error);
    writeJSON(ctx, 500, null, "服务器异常");
  }
});

// 4. 通过id删除用户账号
router.delete("/deleteUserById", async (ctx) => {
  const { _id } = ctx.query;
  await knex("users").where({ _id }).del();
  writeJSON(ctx, 200, null, "删除成功");
});

// 5. 获取所有用户
router.post("/", async (ctx) => {
  const { myroleType, myphone, ...params } = ctx.request.body;
  const users = await knex("users").where(params).select("*");
  users.forEach((user) => {
    if (user.phone !== myphone && user.roleType <= myroleType) {
      user.password = "权限不够，无法查看";
    }
  });
  writeJSON(ctx, 200, users, "获取数据成功！");
});

// 管理员获取普通用户数据
router.post("/common", async (ctx) => {
  const users = await knex("users")
    .where({
      roleType: 2,
    })
    .select("*");
  setResponse(ctx, users);
});

// 5. 编辑一个用户
router.post("/editUser", async (ctx) => {
  const { _id, username, password, email } = ctx.request.body;
  const users = await knex("users")
    .where({ _id })
    .update({ username, password, email });
  ctx.body = users;
});

// 6. 批量编辑用户
router.post("/editUsers", async (ctx) => {
  const { _id, rows } = ctx.request.body;
  const users = await knex("users").where({ _id }).update(rows);
  ctx.body = users;
});

// 7. 验证码
router.get("/captcha", async (ctx) => {
  const captcha = generateCode();
  ctx.body = {
    data: {
      captcha,
    },
  };
});

module.exports = router;
